package com.oscarmovie.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oscarmovie.model.Mpr;
import com.oscarmovie.model.Paging;
import com.oscarmovie.model.Video;

public class VideoDaoImpl extends HibernateDaoSupport implements VideoDao {

	
	public void save(Video video) {
		getSession().saveOrUpdate(video);
	}

	public Video load(int id) {
		Video video = (Video)getSession().load(Video.class, id);
		return video;
	}
	
	
	public void delete(Video video) {
		getSession().delete(video);
	}

	public List<Video> list(Paging paging) {
		paging.setTotalCount((int) count());
		Query query = getSession().createQuery("from Video video");
		query.setCacheable(true);
		query.setFirstResult(paging.getCurrentRow()-1);
		query.setMaxResults(paging.getPageSize());
		List<Video> list = (List<Video>)query.list();
		return list;
	}

	private long count() {
		Query query = getSession().createQuery("select count(*) from Video");
		query.setCacheable(true);
		Long count = (Long) query.uniqueResult();
		return count;
	}
	private long count(int accountId) {
		Query query = getSession().createQuery("select count(*) from Video where account.id = :accountId");
		query.setCacheable(true);
		query.setInteger("accountId", accountId);
		Long count = (Long) query.uniqueResult();
		return count;
	}
	public List<Video> list(Paging paging, int accountId) {
		paging.setTotalCount((int) count(accountId));
		Query query = getSession().createQuery("from Video where account.id = :accountId");
		query.setCacheable(true);
		query.setInteger("accountId", accountId);
		query.setFirstResult(paging.getCurrentRow()-1);
		query.setMaxResults(paging.getPageSize());
		List<Video> list = (List<Video>)query.list();
		return list;
	}
}
